package com.byzk.p2p.admin.task;

import java.util.Date;
import java.util.List;
import java.util.Random;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.byzk.p2p.admin.base.util.BaseUtil;
import com.byzk.p2p.admin.base.util.DateUtils;
import com.byzk.p2p.admin.base.util.PageInfo;
import com.byzk.p2p.admin.borrow.dto.Borrow;
import com.byzk.p2p.admin.borrow.dto.UserTender;
import com.byzk.p2p.admin.borrow.service.BorrowService;
import com.byzk.p2p.admin.borrow.service.TenderService;
import com.byzk.p2p.admin.borrow.util.BorrowStatus;
import com.byzk.p2p.admin.borrow.vo.BorrowVo;
import com.byzk.p2p.admin.fuiou.config.Config;
import com.byzk.p2p.admin.fuiou.dto.TransferToFreezenDto;
import com.byzk.p2p.admin.fuiou.util.SecurityUtils;
import com.byzk.p2p.admin.fuiou.util.WebUtils;
import com.byzk.p2p.admin.fuiou.util.XmlUtils;
import com.byzk.p2p.admin.system.dto.Callback;
import com.byzk.p2p.admin.system.service.CallbackService;
import com.byzk.p2p.admin.user.dto.User;
import com.byzk.p2p.admin.user.service.UserService;

/*** 
* <p>Description:自动满标复审任务</p>
* <p>Company: xbd</p> 
* @author fdq
* @date 2016年9月14日
*/
@Component
public class AutoCheck {
	
	@Autowired
	private BorrowService borrowService;
	@Autowired
	private TenderService tenderservice;
	@Autowired
	private UserService userService;
	@Autowired
	private CallbackService callbackService;
	@Autowired
    private static Logger logger = Logger.getLogger(AutoCheck.class); //日志服务
	/**
     * 定时器每天21：00自动执行一次
     */
//	@Scheduled(cron = "0 0 21 * * ? ")
    public void taskCycle(){
		System.out.println("自动满标复审任务开始==============================开始时间："+DateUtils.getNowTimeString());
		logger.info("自动满标复审任务开始==============================开始时间："+DateUtils.getNowTimeString());
		BorrowVo bVo = new BorrowVo();
		bVo.setStatus(BorrowStatus.CHECK);
		PageInfo<BorrowVo> pageInfo = borrowService.listBorrow(bVo);
		
		logger.info("记录数据总条数("+pageInfo.getPageList().size()+")");
        logger.info("============================开始执行自动满标复审=================================");
        int i =0;
		for(BorrowVo borrowVo : pageInfo.getPageList()) {
			i++;
			Integer borrowId = borrowVo.getId();
			Borrow borrow=borrowService.getBorrowById(borrowId);
			List<UserTender> tenderList=tenderservice.listTender(borrowId);//查找标的投资记录
			BorrowVo vo=borrowService.detailBorrowVo(borrowId);
			User borrowUser=userService.getById(vo.getBorrowUserId());
			int num=0;
			logger.info("自动满标复审，正在处理第["+i+"]笔数据,借款标id=("+borrowId+")");
			for (UserTender userTender : tenderList) {
				User tenderUser=userService.getById(userTender.getUserId());
				TransferToFreezenDto dto=new TransferToFreezenDto();//划拨预冻结
				dto.setMchnt_cd(Config.mchnt_cd);//商户代码
				dto.setMchnt_txn_ssn(DateUtils.getFullFormat()+(new Random().nextInt(8999)+1000));//流水号
				dto.setOut_cust_no(tenderUser.getPhone());//付款登录账户
				dto.setIn_cust_no(borrowUser.getPhone());  //收款登录账户
				dto.setContract_no(userTender.getContractNo());//合同号
				dto.setRem("");
				double amt = BaseUtil.StringToDoubletoFixed2(userTender.getAmount()*100);
				dto.setAmt((int)(amt)+"");
				String inputStr=dto.regSignVal();
				dto.setSignature(SecurityUtils.sign(inputStr));
				
				String backStr = null;
				try {
					backStr = WebUtils.sendHttp(Config.transfer_to_freezen_url,dto);
				} catch (Exception e) {
					logger.info("自动满标复审，正在处理第["+i+"]笔数据的第["+num+"]笔投资用户数据,调用富友接口失败！原因："+e.getMessage());
				}

				System.out.println(backStr);
				logger.info("自动满标复审，正在处理第["+i+"]笔数据的第["+num+"]笔投资用户数据,调用富友接口成功！流水信息："+backStr);
				
				Callback callback=new Callback("划拨预冻结",backStr,new Date());
				callbackService.saveOrUpdate(callback);
				
				String resp_code=XmlUtils.getXmlNodeValue(backStr, "resp_code");
				String mchnt_cd=XmlUtils.getXmlNodeValue(backStr, "mchnt_cd");
				if("0000".equals(resp_code) && Config.mchnt_cd.equals(mchnt_cd)){
					num++;
					logger.info("自动满标复审，正在处理第["+i+"]笔数据的第["+num+"]笔投资用户数据,划拨预冻结成功！投资用户电话=("+tenderUser.getPhone()+"),借款用户电话=("+borrowUser.getPhone()+")");
				}
			}
			if(num==tenderList.size()){
				try {
					tenderservice.compeleteBorrow(borrow);
					logger.info("自动满标复审，正在处理第["+i+"]笔数据,满标自动复审成功！");
				} catch (Exception e) {
					logger.info("自动满标复审，正在处理第["+i+"]笔数据,满标自动复审失败！原因:"+e.getMessage());
				}
			}else{
				logger.info("自动满标复审，正在处理第["+i+"]笔数据,满标自动复审失败！");
			}
		}
		System.out.println("自动任务开始==============================结束时间："+DateUtils.getNowTimeString());
		logger.info("自动任务==============================结束时间："+DateUtils.getNowTimeString());	
	}
}

